package leetcode_700;

/**
 *@author 周杨
 *SolveTheEquation_640 解决一维方程解的问题
 *describe:很无聊 扫描问题 
 *2018年9月25日 上午10:17:04
 */
public class SolveTheEquation_640 {
	public String solveEquation(String equation) {
		boolean passEqualSign = false;
		double leftCoe = 0;
		double rightConst = 0;
		boolean curSignPositive = true;
		double cur = 1;
		boolean validNum = false;
		for (int i = 0; i < equation.length(); i++) {
			char c = equation.charAt(i);
			if (c == '+' || c == '-') {
				if (validNum) {
					if (!passEqualSign) {
						if (curSignPositive)
							rightConst -= cur;
						else
							rightConst += cur;
					} else {
						if (curSignPositive)
							rightConst += cur;
						else
							rightConst -= cur;
					}
				}
				curSignPositive = c == '+' ? true : false;
				validNum = false;
				cur = 1;
			}
			if (Character.isDigit(c)) {
				if (validNum)
					cur = cur * 10 + (double) (c - '0');
				else
					cur = (double) (c - '0');
				validNum = true;
				if (i == equation.length() - 1) {
					if (validNum) {
						if (!passEqualSign) {
							if (curSignPositive)
								rightConst -= cur;
							else
								rightConst += cur;
						} else {
							if (curSignPositive)
								rightConst += cur;
							else
								rightConst -= cur;
						}
					}
				}
			}
			if (c == 'x') {
				if (!passEqualSign) {
					if (curSignPositive)
						leftCoe += cur;
					else
						leftCoe -= cur;
				} else {
					if (curSignPositive)
						leftCoe -= cur;
					else
						leftCoe += cur;
				}
				curSignPositive = true;
				validNum = false;
				cur = 1;
			}
			if (c == '=') {
				if (validNum) {
					if (!passEqualSign) {
						if (curSignPositive)
							rightConst -= cur;
						else
							rightConst += cur;
					} else {
						if (curSignPositive)
							rightConst += cur;
						else
							rightConst -= cur;
					}
				}
				passEqualSign = true;
				curSignPositive = true;
				validNum = false;
				cur = 1;
			}
		}

		if (leftCoe == 0 && rightConst == 0)
			return "Infinite solutions";
		if (leftCoe == 0)
			return "No solution";
		return "x=" + (int) (rightConst / leftCoe);
    }
}
